from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.status import HTTP_404_NOT_FOUND, HTTP_204_NO_CONTENT
from rest_framework.decorators import action

from .models import Student,Department
from .serializers import StudentSerializers,DepartmentSerializer


# Create your views here.
class StudentViewSet(viewsets.ModelViewSet):
    # def list(self, request):
    #     students = Student.objects.all()
    #     serializer = StudentSerializers(instance=students, many=True)
    #     return Response(serializer.data)
    #
    # def create(self, request):
    #     """
    #     获取前端发送过来的数据 进行反序列化
    #     数据校验
    #     保存数据
    #     返回响应
    #     """
    #     serializers = StudentSerializers(data=request.data)
    #     serializers.is_valid(raise_exception=True)
    #     serializers.save()
    #     return Response(serializers.data)
    #
    # def retrieve(self, request, pk):
    #     try:
    #        student = Student.objects.get(id=pk)
    #     except Student.DoesNotExist:
    #         return Response(status=HTTP_404_NOT_FOUND)
    #     serializer = StudentSerializers(student)
    #     return Response(serializer.data)
    #
    # def update(self, request, pk):
    #     """
    #     获取需要修改数据
    #     获取前端传入的数据 反序列化
    #     数据校验
    #     保存
    #     """
    #     try:
    #        student = Student.objects.get(id=pk)
    #     except Student.DoesNotExist:
    #         return Response(status=HTTP_404_NOT_FOUND)
    #     serializer = StudentSerializers(instance=student, data = request.data)
    #     serializer.is_valid(raise_exception=True)
    #     serializer.save()
    #     return Response(serializer.data)
    #
    # def destory(self,request,pk):
    #     """
    #     获取需要删除的数据
    #     删除数据
    #     返回响应
    #     """
    #     try:
    #        student = Student.objects.get(id=pk)
    #     except Student.DoesNotExist:
    #         return Response(status=HTTP_404_NOT_FOUND)
    #     student.delete()
    #     return Response(status=HTTP_204_NO_CONTENT)
    queryset = Student.objects.filter(is_delete=False, department__is_delete=False)
    serializer_class = StudentSerializers

    @action(methods=['get'],detail=False)
    def qurey(self,request):
        student = Student.objects.first()
        serializer = self.get_serializer(student)
        return Response(serializer.data)

class DepartmentViewSet(viewsets.ModelViewSet):
    """
    list:
    查询所有的学院
    """
    queryset = Department.objects.filter(is_delete=False)
    serializer_class = DepartmentSerializer